# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 10:15:47 2018

@author: Who

牛市财经
http://news.one/

"""
import requests
import re
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_Kx(url):
    text = get_html_text(url)
    if not text:
        return None
    regex = re.compile(r'<div class="live-time">(\d{4}.\d{2}.\d{2})</div>')
    dates = re.findall(regex, text)
    return dates


def count_process_one():  # 快讯
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'http://news.one/category/kuaixun/page/{}'
        url = url.format(a)
        dates = get_dates_Kx(url)
        if not dates:
            break
        print('---- 牛市财经快讯获取第{}页----'.format(a))
        for date in dates:
            s = day(date.replace('.', '-'))
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '牛市财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
